package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AuthorityDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = AuthorityService.class)
@Transactional
public class AuthorityServiceImpl  implements AuthorityService{

    @Autowired
    private AuthorityDao authorityDao;
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<User> users = authorityDao.selectByCondition(queryString);

            for (User user : users) {
                Integer userId = user.getId();
              Set<Role> roles = authorityDao.findRoleByUserId(userId);
              user.setRoles(roles);
            }

        long total = users.getTotal();
        List<User> result = users.getResult();
        return new PageResult(total,result);
    }

    @Override
    public LinkedHashSet<Menu> findMenuByUsername(String username) {
        return authorityDao.findMenuByUsername(username);
    }

    @Override
    public List<Menu> findMenuById(Integer id) {
        return authorityDao.findMenuById(id);
    }

    @Override
    public User findUserByUsername(String username) {
        User user =authorityDao.findUserByUsername(username);
        return user;
    }

    @Override
    public List<Integer> findRoleCheckedIdByUsername(String username) {
        return authorityDao.findRoleCheckedIdByUsername(username);
    }

    @Override
    public List<Role> findRoles() {
        return authorityDao.findRoles();
    }

    @Override
    public void edit(Integer[] checkitemIds, User user) {
        Integer id = user.getId();
        //根据用户id删除用户的角色
        authorityDao.deleteByUserId(id);
        //根据用户的id添加权限
        if(checkitemIds!=null && checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Object> map = new HashMap<>();
                map.put("user_id",id);
                map.put("role_id",checkitemId);
                authorityDao.insertRoles(map)
;            }
        }
    }
}
